package com.itaming.lycheeframework.security.authorization;

import com.itaming.lycheeframework.security.exception.AccessDeniedException;
import com.itaming.lycheeframework.support.utils.ClassUtil;
import com.itaming.lycheeframework.support.utils.ObjectUtil;
import com.itaming.lycheeframework.support.utils.StringUtil;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.core.MethodParameter;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;

/**
 * 授权验证切面类
 *
 * @author A.Ming
 */
@Aspect
@RequiredArgsConstructor
public class PreAuthAspect implements ApplicationContextAware {

    /**
     * 表达式解析器
     */
    private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();

    /**
     * Spring上下文
     */
    private ApplicationContext applicationContext;

    /**
     * 授权检查器
     */
    private final AuthorizationChecker authorizationChecker;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 验证
     *
     * @param joinPoint 切点
     * @return 原始方法返回值
     * @throws Throwable
     */
    @Around("@within(com.itaming.lycheeframework.security.authorization.PreAuth)" +
        " || @annotation(com.itaming.lycheeframework.security.authorization.PreAuth)")
    public Object preAuth(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();

        // 获取方法上的权限注解
        PreAuth annotation = ClassUtil.getAnnotation(method, PreAuth.class);

        // 验证权限
        String expressionString = annotation.value();

        // 验证
        if (StringUtil.isNotEmpty(expressionString)) {
            Expression expression = EXPRESSION_PARSER.parseExpression(expressionString);
            StandardEvaluationContext context = getEvaluationContext(method, joinPoint.getArgs());
            Boolean value = expression.getValue(context, Boolean.class);
            if (!ObjectUtil.toPrimitive(value, false)) {
                throw new AccessDeniedException();
            }
        }

        return joinPoint.proceed();
    }

    /**
     * 获取方法参数的上下文
     *
     * @param method 方法
     * @param args   参数
     * @return 上下文
     */
    private StandardEvaluationContext getEvaluationContext(Method method, Object[] args) {
        // 创建上下文
        StandardEvaluationContext context = new StandardEvaluationContext(authorizationChecker);

        // 设置BeanResolver，支持获取SpringBean
        context.setBeanResolver(new BeanFactoryResolver(applicationContext));

        // 设置方法参数
        for (int i = 0; i < args.length; i++) {
            MethodParameter methodParam = ClassUtil.getMethodParameter(method, i);
            context.setVariable(methodParam.getParameterName(), args[i]);
        }

        return context;
    }

}
